//
//  LoginViewController.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 3/7/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//  If it is intented that login screen for information set forStartup to FALSE
//

#import "LoginViewController.h"
#import "LoginRequest.h"
#import "WebServiceCaller.h"
#import "SoapFault.h"
#import "SharedPrefs.h"
#import "NGUtility.h"
#import "NGAppDelegate.h"
#import "LoadingView.h"
#import "Reachability.h"
#import "NSString+Extensions.h"

@implementation LoginViewController


@synthesize usernameField;
@synthesize passwordField;
@synthesize btnLogin;
@synthesize btnCancel;
@synthesize loginIndicator;
@synthesize lblSessionGetting;
@synthesize viewResult;
@synthesize lblResult;
@synthesize imgResult;
@synthesize forStartup;


- (id)init {
    self = [super init];
    if (self) {
        forStartup = TRUE;
    }
    return self;
}

- (void) setCloseCallbackTarget: (id) target {
    closeCallbackTarget = target;
}


#pragma mark - button actions
- (IBAction) login: (id) sender{

    if ([NSString isEmpty:[usernameField text]] || 
        [NSString isEmpty:[passwordField text]]) {
        [NGUtility alertError:TTLocalizedString(@"Enter user name and password", @"")];
        return;
    }
    
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
        [NGAppDelegate alertForNoInternetConnection];
        return;
    }
    NSString *serverUrl = [SharedPrefs getServiceUrlHostName];
    if ([[Reachability reachabilityWithHostName:serverUrl] currentReachabilityStatus] == NotReachable) {
        [NGUtility alertForCannotAccessToURL:serverUrl];
        return;
    }
    
    [usernameField resignFirstResponder];
    [passwordField resignFirstResponder];
    
    [self showActivityViewWith:TTLocalizedString(@"Retrieving Session...", @"") delay:100];

    [loginIndicator setHidden:FALSE];
	[loginIndicator startAnimating];
    [lblSessionGetting setHidden:FALSE];
    [viewResult setHidden:TRUE];
	
    LoginRequest *request = [[[LoginRequest alloc] init] autorelease];
    request.userName = usernameField.text;
    request.password = passwordField.text;
    
    [WebServisCaller callWebServiceLogin:request target:self];
    
    [btnLogin setEnabled:FALSE];
}

- (IBAction) cancel: (id) sender {
    if (forStartup) {
        exit(0);
    } else { 
        if (closeCallbackTarget != nil && [closeCallbackTarget respondsToSelector:@selector(loginClose)]) {
            [closeCallbackTarget loginClose];
        }
        [self.view removeFromSuperview];
    }    
}

#pragma mark - textfield delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - login handler

- (void) loginHandler: (id) value {
    [loginIndicator stopAnimating];
    [loginIndicator setHidden:TRUE];
    [lblSessionGetting setHidden:TRUE];
    [btnLogin setEnabled:TRUE];
    
    [viewResult setHidden:FALSE];
    [lblResult setText:TTLocalizedString(@"Invalid", @"")];
    [imgResult setImage:[UIImage imageNamed: @"ic_fail.png"]];
    
    [self hideActivityView];

    if ([NGUtility handleRequestForError:value showAlert:TRUE]) {
        return;
    }
    

	NSLog(@"%@ login returned the value: %@\n", @"LoginViewController", value);
    
    if ([NSString isEmpty:value]) {
        [lblResult setText:TTLocalizedString(@"Invalid", @"")];
        [imgResult setImage:[UIImage imageNamed: @"ic_fail.png"]];        
    } else {
        [lblResult setText:TTLocalizedString(@"Valid", @"")];
        [imgResult setImage:[UIImage imageNamed: @"ic_check.png"]];  
        [SharedPrefs setSessionID:value];
        [SharedPrefs setUserName: usernameField.text];
        [SharedPrefs setPassword: passwordField.text];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults synchronize];
        if (forStartup) {
            NGAppDelegate *appDelegate = (NGAppDelegate *) [[UIApplication sharedApplication] delegate];
            [appDelegate enter];
        }
    }   
}

#pragma mark - touch delegate

-(void) defineGesture {
    UITapGestureRecognizer *touchOnImgUsername = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pressToImages:)] autorelease];
    
    UITapGestureRecognizer *touchOnImgPassword = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pressToImages:)] autorelease];
    
    [touchOnImgUsername setNumberOfTapsRequired:1];
    [touchOnImgUsername setNumberOfTouchesRequired:1];
    [touchOnImgPassword setNumberOfTapsRequired:1];
    [touchOnImgPassword setNumberOfTouchesRequired:1];
    
    [imgUsername addGestureRecognizer:touchOnImgUsername];
    [imgPassword addGestureRecognizer:touchOnImgPassword];    
}

-(void)pressToImages:(UITapGestureRecognizer*)recognizer {
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        if ([recognizer view] == imgUsername)
            [usernameField becomeFirstResponder];
        else if ([recognizer view] == imgPassword)
            [passwordField becomeFirstResponder];
    }
}

#pragma mark - initialization

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        nibNameOrNil = [nibNameOrNil stringByAppendingString:@"-ipad"];
    }
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        forStartup = TRUE;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    
    [btnLogin setTitle:TTLocalizedString(@"OK", @"") forState:UIControlStateNormal];
    [lblUsername setText:TTLocalizedString(@"User name", @"")];
    [lblPassword setText:TTLocalizedString(@"Password", @"")];
    
    [usernameField setText:[SharedPrefs getUserName]];
    [passwordField setText:[SharedPrefs getPassword]];
    
    [self defineGesture];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    //check for internet connection
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
        [NGAppDelegate alertForNoInternetConnection];
        return;
    }
    
    if (forStartup) {
        [self login:btnLogin];
    }    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc {
    [usernameField release];
    [passwordField release];
    [loginIndicator release];
    [lblUsername release];
    [lblPassword release];
    [btnCancel release];
    [btnLogin release];
    [btnLogin release];
    //[super dealloc];
}

@end
